<?php
	/**
	 * General purpose functions
	 * 
	 * @author Austin Laugesen <austin-laugesen@uiowa.edu>
	 * @version 1.0
	 * @package unknown
	 */
		
	/** 
	 * config.php contains all config information
	 */
	require_once('config.php');
	require_once('database.php');
	require_once('constants.php');

	/**
	 * Build a list of links that should be displayed above the user's Accounts table
	 * @return string navigation 
	 */
	function makeAccountNavBar($id){
		global $ACCOUNTS_URL, $TRANS_URL, $SELECTED_USER_ID;
		$navStr = '';
		$id = 0;
		
		if(true == isBankManager()){ 
			if(true == isset($_SESSION[$SELECTED_USER_ID])){
				if($_SESSION[$SELECTED_USER_ID] != $_SESSION['id']){
					$id = $_SESSION[$SELECTED_USER_ID];
					$userInfo = getUserInfo($id);
					$navStr .='<a href="' . $ACCOUNTS_URL . 'index.php?'.$SELECTED_USER_ID.'=' . $id . '" >' 
					. $userInfo['firstname'] . '\'s Overview' . '</a> | '
					. '<a href="' . $TRANS_URL . 'withdraw.php?'.$SELECTED_USER_ID.'=' . $id . '">Withdraw</a> | '
					.'<a href="' . $TRANS_URL . 'deposit.php?'.$SELECTED_USER_ID.'=' . $id . '">Deposit</a> | ';
					$navStr .= '<a href="' . $TRANS_URL . 'transfer.php?'.$SELECTED_USER_ID.'=' . $id . '">Transfer</a> | '
					. '<a href="' . $ACCOUNTS_URL . 'add.php?'.$SELECTED_USER_ID.'='. $id .'" >Create New Account</a><br/><br/>';
				}
			}
			else{
					// TODO - the admin hasn't selected a user - we should probably fail!
			}
		} else if (true == isCustomer()){
			$id = $_SESSION['id'];
			$userInfo = getUserInfo($id);
			$navStr .='<a href="' . $ACCOUNTS_URL 
			//. 'index.php?'.$SELECTED_USER_ID.'=' . $id . '" >' . $userInfo['firstname'] . '\'s Overview' . '</a> | ';
			. 'index.php?'.$SELECTED_USER_ID.'=' . $id . '" >Your Overview' . '</a> | ';
			$navStr .= '<a href="' . $TRANS_URL . 'transfer.php?'.$SELECTED_USER_ID.'=' . $id . '">Transfer</a> | '
			. '<a href="' . $ACCOUNTS_URL . 'add.php?'.$SELECTED_USER_ID.'='. $id .'" >Create New Account</a><br/><br/>';
		}
		
		return $navStr;
		
	}
	
	function getID(){
		global $SELECTED_USER_ID;
		// Assume the logged in user is a customer
		$id = $_SESSION['id'];
		
		// If the user logged in is not a customer we need to retreive the customer's ID
		// because we'll use the customer's ID to pull of info we care about.
		if(false == isCustomer()){ // bank manager or admin
			if(true == isset($_GET[$SELECTED_USER_ID])){
				$id = $_GET[$SELECTED_USER_ID];
				$_SESSION[$SELECTED_USER_ID] = $id;
			}
			else{
				$id = $_SESSION[$SELECTED_USER_ID];
			}
		}
		return $id;
	}
	
	/**
	 * @return string navigation
	 */
	function makeUserNavBar(){
		global $USERS_URL;
		return '<a href="' . $USERS_URL . 'add.php" >Create New User</a><br/><br/>';
	}
	
	/**
	 * Generate a navigation bar for the website - discriminate based on user role
	 *
	 * @param string $page
	 * @return string
	 */
	function makeNavBar($siteTitle = '', $header = False){
		global $SITE_URL, $ACCOUNTS_URL, $USERS_URL, $AUTH_URL;

		// These links will be created regardless if the browser is Mobile or PC
		$navStr = '<ul><li><a href="' . $SITE_URL . '" >Home</a></li>';
		
		if(False == $header){
			$navStr .= '<li><a href="' . $SITE_URL . 'locationAndHours.php" >Location & Hours</a></li>';
			$navStr .= '<li><a href="' . $SITE_URL . 'about.php" >About</a></li>';
			$navStr .= '<br/>';
		}
		
		if(isMobile()){
			if (true == isCustomer()){
				$navStr .= '<li><a href="' . $ACCOUNTS_URL .  '">Accounts</a></li>';
			}
			// else we don't have to generate any other links... 
			// Bank Managers & admins aren't allowed to access their features on mobile
		}
		// The user is on a PC Browser
		else{
			if (true == isCustomer()){
				$navStr .= '<li><a href="' . $ACCOUNTS_URL .  '">Accounts</a></li>';
				$navStr .= '<li><a href='. $USERS_URL . 'edit.php >Edit Profile</a></li>';
			}
			else if(true == isAdmin() || true == isBankManager()){
				$navStr .= '<li><a href="' . $USERS_URL . '" >Users</a></li>';
			}
			if(isLoggedIn()){
			  $navStr .= '<li><a href="' . $AUTH_URL . 'logout.php" >Logout</a></li>';
			}
			else{
			  $navStr .= '<li><a href="' . $AUTH_URL . '" >Sign in</a></li>';
			}
			$navStr .= '</ul>';
		}
		return $navStr;
	}

	/**
	 * Associative array of User column names and column descriptions.
	 * @return array
	 */
	function getUserAttributes(){
		return array('firstname'=>'First Name',
					 'lastname'=>'Last Name',
					 'email'=>'Email',
					 'address'=>'Address',
					 'city'=>'City',
					 'state'=>'State',
					 'dob'=>'Date of Birth',
					 'ssn'=>'SSN',
					 'passwordhash'=>'Password',
					 'confirmPassword'=>'Confirm Password',
					 'question'=>'Security Question',
					 'answerhash'=>'Answer',
					 'accountNumber'=>'Account #',
					 'roleid'=> 'Role ID',
					 'active'=>'Active');
	}

	/**
	 * Associative array of Account column names and column descriptions.
	 * @return array
	 */
	function getAccountAttributes(){
	  return array('number'=>'Number',
				   'userid'=>'user id',
				   'type'=>'Type',
  				   'minimum'=>'Minimum',
				   'balance'=>'Balance',
				   'active'=>'Active');
	}

	/**
	 * Associative array of Transaction column names and column descriptions.
	 * @return array
	 */
	function getTransactionAttributes(){
	  return array('accountid'=>'Account ID', 
				   'date'=>'Date',
				   'type'=>'Type', 
				   'amount'=>'Amount',
				   'balance'=>'Balance');
	}

	/**
	 * Builds the string that contains paths to all of the javascript files. This string goes into the HTML Header.
	 * @return string
	 */
	function getJavascript(){
		global $SITE_URL;
		return '<script type="text/javascript" src="' . $SITE_URL .'js/base.js"></script>
		<script type="text/javascript" src="' . $SITE_URL .'js/cufon-yui.js"></script>
		<script type="text/javascript" src="' . $SITE_URL .'js/cufon-colaborate-800.js"></script>
		<script type="text/javascript" src="' . $SITE_URL .'js/jquery-1.4.2.min.js"></script>
		<script type="text/javascript" src="' . $SITE_URL .'js/script.js"></script>
		<script type="text/javascript" src="' . $SITE_URL .'js/coin-slider.min.js"></script>
		<script type="text/javascript" src="' . $SITE_URL .'js/jquery-ui-1.8.16.custom.min.js"></script>
		<!--<script type="text/javascript" src="' . $SITE_URL .'js/jquery-1.6.2.min.js"></script>-->'
		;
	}

	/**
	 * Standard string replacements to generate default site content look and feel
	 */
	function buildStandardPage($pageTitle = '', $siteTitle = ''){
		global $SITE_PATH, $SITE_URL, $CSS_URL, $CSS_URL2, $CSS_MOBILE_URL;
		
		$pageStr = NULL;
		
		if(isMobile()){
			// Get the base HTML for Mobile browsers
			$pageStr = file_get_contents($SITE_URL . 'templates/mobile.html');
			
			// Get the CSS for Mobile browsers
			$pageStr = str_Replace('<!--cssURL-->', $CSS_MOBILE_URL, $pageStr);
			return $pageStr;
		}
		else{
			// Get the base HTML for PC browsers
			$pageStr = file_get_contents($SITE_URL . 'templates/index.html');
			
			$pageStr = str_Replace('<!--navbarHeader-->', makeNavBar('', True), $pageStr);
			
			// Get the CSS for PC browsers
			$pageStr = str_Replace('<!--cssURL-->', $CSS_URL, $pageStr);
			$pageStr = str_Replace('<!--cssURL2-->', $CSS_URL2, $pageStr);
			
		}
		
		$pageStr = str_Replace('<!--base-->', $SITE_URL, $pageStr);
		$pageStr = str_Replace('<!--sitetitle-->',$siteTitle, $pageStr);
		$pageStr = str_Replace('<!--navbar-->', makeNavBar($siteTitle), $pageStr);
		$pageStr = str_Replace('<!--siteURL-->', $SITE_URL, $pageStr);
		$pageStr = str_Replace('<!--javascript-->', getJavascript(), $pageStr);
		$pageStr = str_Replace('<!--pageTitle-->', $pageTitle, $pageStr);
		
		return $pageStr;
	}

	/**
	 * Cleanse the information submitted by a user to the website
	 * @param string $post
	 * @return string
	 */
	function cleanPost($post){
		foreach($post as $key => $value){
		  $post[$key] = htmlentities(mysql_escape_string($value));
		}
		
		return $post;
	}

	/**
	 * Check if the user is currently logged in
	 * @return boolean
	 */
	function isLoggedIn(){
		return isset($_SESSION['id']);
	}
	
	function isActive(){
		if(isLoggedIn()){
			return (1 == $_SESSION['active']);
		}
		return false;
	}

	/**
	 * This is a helper function for isAdmin, isBankManager and isCustomer
	 * @return boolean
	 */	
	function isRole($id){
	   if(isLoggedIn()){
		   
		   // to avoid querying the DB too much we'll store the user's role id 
		   // in the session variable after we retrieve it the first time
		   if(false == isset($_SESSION['roleid'])){
				$user = getLoggedInUser();
			   
				$_SESSION['roleid'] = $user['roleid'];
			   
			    // set the is active variable
				$_SESSION['active'] = $user['active'];
			   
				if($id == $_SESSION['roleid']){
					return true;
				}
		   }
		   else{
			   if($id == $_SESSION['roleid']){
				   return true;
			   }
		   }
		}
		return false;
	}

	/**
	 * Check if the currently logged in user is website administrator 
	 * @return boolean
	 */
	function isAdmin(){
	  return isRole(0);
	}

	/**
	 * Check if the logged in user is a bank manager
	 * @return boolean
	 */
	function isBankManager(){
	  return isRole(1);
	}

	/**
	 * Check if the logged in user is a customer
	 * @return boolean
	 */
	function isCustomer(){
	  return isRole(2);
	}
	
	function buildAccountTable($id){
		global $SITE_URL, $ACCOUNTS_URL, $SELECTED_USER_ID, $ACCOUNT_ID, $DELETE_ACCOUNT_URL, $ACTIVATE_ACCOUNT_URL;
		$accountAttribs = getAccountAttributes();
		$userInfo = getUserInfo($id);
		$result = getAccounts($id);
		
		$table = '<table border=1 cellpadding=2 width=650>';
		$table .= '<tr>';
		foreach($accountAttribs as $fieldName => $description){
			if ($fieldName != 'userid' && $fieldName != 'active' && $fieldName != 'type'){
				$table .= '<td>' . $description . '</td>';
			}
		}
		
		if(true == isBankManager()){
			$table .= '<td colspan=2><center>Modify</center></td>';
		}
		$table .= '</tr>';
		
		$networth = 0;
		$accountNumber = 1;
		
		$savingsTable = '';
		$checkingTable = '';
		$inactiveTable = '';
		$inactiveCount = 0;
		$checkingCount = 0;	
		
		$numRows = mysql_num_rows($result);
		$countDown = $numRows;
		while($row = mysql_fetch_array($result)){
			$tmpRow = '<tr>';
			$isActive = false;
			$isSavings = false;

			foreach($accountAttribs as $fieldName => $description){
				switch($fieldName){
					case 'userid':
						break;
					case 'number':
						$num = (($row['active'] == 1) ? $accountNumber++ : $countDown--);
						
						$tmpRow .= '<td><a href='. $ACCOUNTS_URL 
						. 'view.php?'. $ACCOUNT_ID .'=' . $row['id'] 
						. '&accountNum=' . $userInfo['accountNumber'] . '-' . $num
						. '&id=' . $id
						. ' >' . $userInfo['accountNumber'] . '-' . $num
						. '</a></td>';						
						break;
					case 'type':
						$isSavings = ($row[$fieldName] == 'Savings');
						break;
					case 'balance':
						$tmpRow .= '<td> $' . $row[$fieldName] . '</td>';  
						$networth += $row[$fieldName];						
						break;
					case 'active':
						$isActive = ($row['active'] == 1);
						break;
					default:
						$tmpRow .= '<td>' . $row[$fieldName] . '</td>';
						break;
				}
			}
			if(true == isBankManager()){
				if(true == $isActive){
					$tmpRow .= '<td colspan=2><center><a href="' . $DELETE_ACCOUNT_URL . '?'.$ACCOUNT_ID.'='.$row['id'] .'">Delete</center></a></td>';
				}
				else{
					$tmpRow .= '<td><a href="' . $ACTIVATE_ACCOUNT_URL . '?'.$ACCOUNT_ID.'='.$row['id'] .'">Activate</a></td>'
							. '<td><a href="' . $DELETE_ACCOUNT_URL . '?'.$ACCOUNT_ID.'='.$row['id'] .'">Delete</a></td>';				
				}
			}else if(true == isCustomer()){
				if(false == $isActive){
					$tmpRow .= '<td colspan=2><center><a href="' . $DELETE_ACCOUNT_URL . '?'.$ACCOUNT_ID.'='.$row['id'] .'">Delete</center></a></td>';
				}
			}
			
			$tmpRow .= '</tr>';
			
			if(true == $isActive){
				if(true == $isSavings){
					$savingsTable .= $tmpRow;
				}
				else{
					$checkingTable .= $tmpRow;
					$checkingCount++;
				}
			}
			else{
				
				$inactiveCount += 1;

				$inactiveTable .= $tmpRow;

			}
			//$accountNumber++;
		}
		mysql_free_result($result);
		
		$content = '<h2>Savings</h2>' . $table . $savingsTable .'</table>';
		
		$content .= '<h2>Checking</h2>';
		if(0 < $checkingCount){
			$content .= $table . $checkingTable .'</table>';
		}
		else{
			$content .= '<p>You may want to consider opening a checking account.</p>';
		}
		$content .= '<br/><table border=1 cellpadding=2 width=650><tr><td><strong>Net Worth:</strong></td><td><strong>$' . $networth . '</strong></td></tr></table><br/>';

		if(0 < $inactiveCount){
			$content .= '<h2>Inactive Accounts</h2>Please go to the nearest physical bank to have these accounts activated.<br/><br/>';
			
			$table = '<table border=1 cellpadding=2 width=650>';
			$table .= '<tr>';
			foreach($accountAttribs as $fieldName => $description){
				if ($fieldName != 'userid' && $fieldName != 'active' && $fieldName != 'type'){
					$table .= '<td>' . $description . '</td>';
				}
			}
			$table .= '<td colspan=2><center>Modify</center></td></tr>';
			
			$content .= $table. $inactiveTable .'</table>';
		}
		
		return $content;
	}
	
	function buildUserTable(){
		global $USERS_URL, $ACCOUNTS_URL, $SELECTED_USER_ID;
		$content = '<table border=1 cellpadding=2 width=650>'
				. '<tr>';
		
		// making a mapped array to facilitate processing the query results
		// the key in each array entry is the field name
		// the value in each array entry is the description for the column headings
		$userDescriptionArray = getUserAttributes();
		
		
		/*
		 return array('firstname'=>'First Name',
		 'lastname'=>'Last Name',
		 'email'=>'Email',
		 'address'=>'Address',
		 'city'=>'City',
		 'state'=>'State',
		 'dob'=>'Date of Birth',
		 'ssn'=>'SSN',
		 'passwordhash'=>'Password',
		 'confirmPassword'=>'Confirm Password',
		 'securityQuestion'=>'SecurityQuestion',
		 'answerHash'=>'Answer',
		 'accountNumber'=>'Account #',
		 'roleid'=> 'Role ID',
		 'active'=>'Is Active');
		 */
		
		// We don't need these values for building our table
		unset($userDescriptionArray['passwordhash']);
		unset($userDescriptionArray['confirmPassword']);
		unset($userDescriptionArray['address']);
		unset($userDescriptionArray['city']);
		unset($userDescriptionArray['state']);
		unset($userDescriptionArray['dob']);
		unset($userDescriptionArray['ssn']);
		unset($userDescriptionArray['question']);
		unset($userDescriptionArray['answerhash']);
		
		foreach($userDescriptionArray as $description) {
//			if($description != 'Password' && $description != 'Confirm Password'){
				$content .= '<td><center><strong>' . $description . '</strong></center></td>';
//			}
		}
		
		$content .= '<td colspan=2><center><strong>Profile</strong></center></td>';
		if(true == isBankManager()){
			$content .= '<td colspan=1><center><strong>Account</strong></center></td>';
		}
		$content .= '</tr>';
		
		// Get all of the users
		$query = buildSelectStatement('user', array());
		$result = executeSQL($query, 'Failed to retrieve any users from the database.');
		
		// using the query results and $userDescriptionArray to produce HTML
		while($row = mysql_fetch_array($result)) 
		{
			$content .= '<tr>';
			
			foreach($userDescriptionArray as $fieldName => $description) {
				if('roleid' == $fieldName){
					$content .= '<td><center>';
					switch($row[$fieldName]){
						case 0:
							$content .= 'Admin';
							break;
						case 1:
							$content .= 'Manager';
							break;
						case 2:
							$content .= 'Customer';
							break;
						default:
							$content .= 'Unknown';
					}
					$content .= '</td></center>';
				}
				else if('active' == $fieldName){
					$content .= '<td><center>';
					switch($row[$fieldName]){
						case 0:
							$content .= 'Inactive';
							break;
						case 1:
							$content .= 'Active';
							break;
						default:
							$content .= 'Unknown';
					}
					$content .= '</td></center>';
				}
				else if('accountNumber' == $fieldName){
					if(2 == $row['roleid']){
						$content .= '<td><center>' . $row[$fieldName] .'</center></td>';
					}
					else{
						$content .= '<td><center>N/A</center></td>';
					}
				}
				else {	
					$content .= '<td><center>' . $row[$fieldName] .'</center></td>';
				}
			}
			
			if(true == isAdmin()){
				$content .= '<td><center><a href=' . $USERS_URL . 'edit.php?'.$SELECTED_USER_ID.'=' . $row['id'] . '>Edit</a></center></td>'
						.'<td><center><a href=' . $USERS_URL . 'delete.php?'.$SELECTED_USER_ID.'=' . $row['id'] . '>Delete</a></center></td>';
			}
			else{ // Must be a bank manager
				$content .= '<td colspan=2><center><a href=' . $USERS_URL . 'edit.php?'.$SELECTED_USER_ID.'=' . $row['id'] . '>Edit</a></center></td>';
				if(2 == $row['roleid']){
					$content .= '<td><center><a href=' . $ACCOUNTS_URL . 'index.php?'.$SELECTED_USER_ID.'=' . $row['id'] . '>View</a></center></td>';
				}
				else{
					$content .= '<td><center>N/A</center></td>';
				}
			}
			$content .= '</tr>';
		}
		$content .= '</table>'; 
		return $content;
	}
	
	
	function populateAccountsForTable($id, $arr = array('Account'=>'aid')){
		global $ACCOUNT_ID;
		$userInfo = getUserInfo($id);
		
		$content = '';
		foreach($arr as $accountLabel => $accountName){
			$userAccounts = getAccounts($id);
			
			// List accounts in a selection - to withdraw from
			$content .= '<tr><td>'. $accountLabel .'</td><td><select name='.$accountName.' >';
			$accountNumber = 1;
			while($row = mysql_fetch_array($userAccounts)){	
				if(true == $row['active']){
					$content .= '<option value="' . $row['id'] .'-'.$row['balance'].'">' 
					. $userInfo['accountNumber'] . '-' .$accountNumber . ' ......... $' . $row['balance'] 
					.'</option>';
				}
				$accountNumber++;
			}
		}
		$content .= '</select></tr>';
		return $content;
	}
	
	/**
	 * Check if the user is on a mobile browser
	 * @return boolean
	 */
	function isMobile(){
		
		// make sure we haven't already determined if the user's browser is mobile 
		if(False == isset($_SESSION['mobile'])){
			$mobile_browser = 0;
			
			if (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android)/i', strtolower($_SERVER['HTTP_USER_AGENT']))) {
				$mobile_browser++;
			}
			if ((strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') > 0) or ((isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE'])))) {
				$mobile_browser++;
			}    
			$mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'], 0, 4));
			$mobile_agents = array(
								   'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
								   'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
								   'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
								   'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
								   'newt','noki','oper','palm','pana','pant','phil','play','port','prox',
								   'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
								   'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
								   'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
								   'wapr','webc','winw','winw','xda ','xda-');
			
			if (in_array($mobile_ua,$mobile_agents)) {
				$mobile_browser++;
			}
			
			/*if (strpos(strtolower($_SERVER['ALL_HTTP']),'OperaMini') > 0) {
				$mobile_browser++;
			}*/
			
			if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'windows') > 0) {
				$mobile_browser = 0;
			}
			
			if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows phone') > 0){
				$mobile_browser++;
			}
			
			
			$_SESSION['mobile'] = ($mobile_browser > 0);
		}
		return $_SESSION['mobile'];
	}
	
	/**
	 * Options commonly used in forms
	 */
	function getUserRolesAsOptions($selected = 2){		
		return '<tr><td>Role ID' 
		. '</td><td><select name=roleid ' //. (true == isAdmin() ? 'disabled="disabled"' : '') 
		. '><option value="2" ' . (($selected == 2) ? 'selected="selected"' : '') . ' >Customer</option>'
		.'<option value="1" ' . (($selected == 1) ? 'selected="selected"' : '') . '>Bank Manager</option>'
		.'<option value="0" ' . (($selected == 0) ? 'selected="selected"' : '') . '>Admin</option></select></td></tr>';
	}
	
	function getActiveOptions($selected = 0){
		return '<tr><td>Active' 
		. '</td><td><select name=active ' //. (true == isAdmin() ? 'disabled="disabled"' : '') 
		. '><option value="1" ' . (($selected == 1) ? 'selected="selected"' : '') . '>Active</option>'
		.'<option value="0" ' . (($selected == 0) ? 'selected="selected"' : '') . '>Inactive</option>'
		.'</select></td></tr>';		
	}
	
	function getStatesAsOptions($forceEnabled = false, $selected = 'IA'){
		global $SELECTED_USER_ID;
		$states = array('IA'=>'Iowa', 'WI'=>'Wisconsin','IL'=>'Illinois');
		$str = 'State</td><td><select name=state >';//. ((true == isAdmin() && ($_SESSION[$SELECTED_USER_ID] != $_SESSION['id']) && !$forceEnabled) ? 'disabled="disabled"' : '' ) .'>';
		foreach($states as $abbrev => $name){
			$str .= '<option value="' . $abbrev . '" ' 
			     . (($selected == $abbrev) ? 'selected="selected"' : '') 
			. ' >' . $name . '</option>';
		}
		
		$str .= '</select></td></tr>';
		return $str;
	}	
?>